#include <iostream>
#include <thread>
#include <vector>
#include <mutex>
#include <atomic>

class Counter {
public:
    Counter() : count(0) {
        std::cout << " init counter ..." << std::endl;
    }

    void increment(int iterations) {
        std::cout << "incrtement ..." << std::endl;

        while (true)
        {
            std::lock_guard<std::mutex> lock(mutex);
            std::unique_lock<std::mutex> lock(mutex);

            if (count >= iterations) {
                break;    // 以达到目标，退出循环
            }

            ++count;
        }
        
    }

    int getCount() const {
        std::lock_guard<std::mutex> lock(mutex);
        return count;
    }

private:
    int count;
    // mutable std::atomic<int> count;
    mutable std::mutex mutex;

};

// 线程函数，用于增加计数器的值
// void incrementCounter(Counter& counter, int iterations) {
//     for (int i = 0; i < iterations; ++i) {
//         counter.increment();
//     }
// }

int main() {
    const int numThreads = 4;
    const int iterationsPerThread = 100000;

    Counter counter;
    std::vector<std::thread> threads;

    // 启动多个线程
    for (int i = 0; i < numThreads; ++i) {
        // 加入4个线程
        threads.emplace_back(&Counter::increment, std::ref(counter), iterationsPerThread);
    }

    // 等待所有线程完成
    for (std::thread& thread : threads) {
        thread.join();
    }

    // 打印最终计数器值
    std::cout << "Final Count: " << counter.getCount() << std::endl;

    return 0;
}